package au.com.somethingwritten.model;

import static org.junit.Assert.*;

import java.util.ArrayList;

import org.junit.Test;

public class BookDAOTest {
	
	@Test
	public void testGetAllBooks() {
		ArrayList<Book> allBooks = new ArrayList<Book>();
		try{
			allBooks = BookDAO.getAllBooks();
		}catch (Exception e){
			fail(e.getMessage());
		}
		
		for(int i = 0; i < allBooks.size(); i++){
			System.out.println(allBooks.get(i).toString());
		}
		
		//make sure an object is returned.
		assertNotNull("No results returned", allBooks);
		
		//make sure the object has some results in it.
		if(allBooks.size() < 1){
			fail("Empty result set");
		}
	}
	
	@Test
	public void testUpdateBookQuantity() {
		ArrayList<Book> allBooks = new ArrayList<Book>();
		//get all the books
		try{
			allBooks = BookDAO.getAllBooks();
		}catch (Exception e){
			fail(e.getMessage());
		}
		
		//select any book (in this case the first)
		Book tmp = allBooks.get(0);
		System.out.println(tmp.toString());
		
		//reduce the number of copies.
		tmp.sellCopies(1);
		
		//update database 
		try{
			assertEquals("Number of rows updated != 1", 1, BookDAO.updateBookQuantity(tmp));
		}catch(Exception updateErr){
			fail(updateErr.getMessage());
		}
		
		//get books from db again
		try{
			allBooks = BookDAO.getAllBooks();
		}catch (Exception e){
			fail(e.getMessage());
		}
		//find the book that was updated
		Book updatedBook = null;
		for(int i = 0; i < allBooks.size(); i++){
			if(allBooks.get(i).getId() == tmp.getId())
				updatedBook = allBooks.get(i);
		}
		
		//make sure the updated book was found
		assertNotNull("Updated book not found", updatedBook);
		
		//make sure the number of copies was updated
		assertEquals("Quantity did not update", tmp.getQuantity(),updatedBook.getQuantity());
		
		//reset the number of quantities
		updatedBook.setQuantity(updatedBook.getQuantity() + 1);
		
		//update database 
		try{
			assertEquals("Number of rows updated != 1", 1, BookDAO.updateBookQuantity(updatedBook));
		}catch(Exception updateErr){
			fail(updateErr.getMessage());
		}
	}

}
